/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 * 
 * @file: Ancestor.Base.js
 * @path: js-src/Ancestor/
 * @desc: Ancestor模块下基础业对象类
 * @author: lichuning@qiyi.com
 * @date: 2013-04-10
 */
///import js-src/lib/
///import js-src/com/

qui(function(require, exports, module) {

    Ancestor.Grid = function(options) {};
    /**
     * 每个Action都设置一个初始化方法 用于初始化Ancestor 原型对象，默认不重复初始化
     *
     * @param {Boolean}
     *            force 是否强制初始化
     *
     */
    Ancestor.Grid.prototype = $.extend(true, {}, Com.Grid, {
        filterDataWhenBatchOper: function(data, filter) {
            filter = filter || function(item) {
                return !item.del;
            };

            data = $.grep(data, function(item) {

                return filter(item);
            });

            return data;
        },
        /**
         * 素材库查询方法
         * @param params 查询参数，采用jquery formSerialize
         * @param callback
         */
        query: function(callback) {

            var self = this;
            var $grid = self.$grid;

            var params = this.getParam();

            $grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid', [{
                page: 1
            }]);

        },
        getParam: function() {

            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            Com.Grid.overridePostData($grid);
            var params = {};
            var $elements = $.makeArray($container.find('form.query').prop('elements'));

            $.each($elements, function() {
                if (this.name) {
                    var key = $(this).attr('data-key');
                    if (key) {
                        params[this.name] = $(this).attr(key) || '';
                    } else {
                        params[this.name] = $(this).val();
                    }
                }
            });

            return params;
        },

        echoQuery: function() {
            var self = this;
            var $container = self.options.$container;

            this.query();

        },

        getGrid: function() {
            return this.$grid;
        },

        run: function(options, callback) {


            this.bindEvent();
            this.echoQuery();
            this.initGrid.call(this, options, callback);

        },

        setType: function(type) {
            this.options.type = type;
        },

        getType: function() {
            return this.options.type;
        },

        getGridConfig: function(table, tableColModel) {
            var self = this;
            var tableConfig = $.extend(true, {}, table || self.config.TABLE);
            var colModel = tableConfig.colModel;
            var newColModel = [];
            var colModelConfig = tableColModel || self.config.TABLE_COLMODEL_CONFIG;

            $.each(colModel, function(i, model) {
                newColModel.push(colModelConfig[model]);
            });
            tableConfig.colModel = newColModel;
            return tableConfig;
        },

        initGrid: function(options, callback) {
            var self = this;

            var gridConfig = self.getGridConfig();

            var $gridContainer = self.options.$container;

            var type = self.getType();
            var $pager = $gridContainer.find('div.pager');
            var $grid = $gridContainer.find('table.grid');
            var params = self.getParam();
            options = $.extend(true, {
                pager: $pager,
                mtype: 'post',

                postData: $.extend(true, {
                    type: type

                }, params),

                sortname: 'createTime',
                sortorder: 'desc',


                multiselect: true,

                multiselectWidth: 30

            }, gridConfig, options);

            $grid.jqGrid('scroll', {});
            $grid.jqGrid(options);

        },

        bindEvent: function() {
            var self = this;
            var $container = this.options.$container;
            var $form = $container.find('form[name="basicFrm"]');

            /*
             * 绑定时间
             *
             */
            //$.datepicker.setDefaults( $.datepicker.regional[ "" ] );

            $container.find("#StartTime").datetimepicker({
                onClose: function(selectedDate) {
                    $("#EndTime").datepicker("option", "minDate", selectedDate);
                }

            });

            $container.find("#EndTime").datetimepicker({
                onClose: function(selectedDate) {
                    $("#StartTime").datepicker("option", "maxDate", selectedDate);
                }
            });

            $form.find('button[type="reset"]').click(function() {
                self.resetQueryForm();
            });
        },

        resetQueryForm: function() {
            var self = this;
            var $container = this.options.$container;
            var $form = $container.find('form[name="basicFrm"]');
            // 从suggest获得的数据都需要清空
            $form.find('input[data-key]').removeAttr('data-id');
        },

        reload: function(params) {
            var type = this.getType();
            params = $.extend(true, {
                type: type
            }, params);
            this.$grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid');
        },

        // 基本数据请求队列
        ajaxBasicRequestQueue: (function() {
            var Queue = [];

            var pushData = function(obj) {
                Queue.push(obj);
            };
            var getQueueLen = function() {
                return Queue.length;
            };
            var getQueueData = function() {
                return Queue;
            };
            var clearQueueData = function() {
                Queue = [];
            };

            return {
                pushData: pushData,
                getQueueLen: getQueueLen,
                getQueueData: getQueueData,
                clearQueueData: clearQueueData
            };

        })(),

        ajaxBasicRequestLen: -1,
        intverId: null,

        // 处理请求队列
        ajaxBasicRequestManage: (function() {

            var self = null,
                fct = null,
                tryNumbers = 10000; //尝试10000次

            var init = function(obj, func) {
                self = obj;
                fct = func;
                start();
            };

            var start = function() {
                var len = self.ajaxBasicRequestQueue.getQueueLen();
                if (len === 0) return;

                if (self.ajaxBasicRequestLen == len || tryNumbers == 1) {
                    clearInterval(self.intverId);
                    fct(self);
                    self.ajaxBasicRequestQueue.clearQueueData();
                } else if (self.ajaxBasicRequestLen != -1) {
                    return;
                } else {
                    var queue = self.ajaxBasicRequestQueue.getQueueData();
                    self.ajaxBasicRequestLen = 0;

                    $.each(queue, function(i, item) {
                        item.func(function() {
                            self.ajaxBasicRequestLen++;
                        });
                    });
                    self.intverId = setInterval(start, 10);
                }
                tryNumbers--;
            };
            return {
                init: init
            };
        })(),
    });

});